/*
 * Author: kael http://weibo.com/loskael
 */
package los.kael.image;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

/**
 * 
 * @author kael http://weibo.com/loskael
 * @version $FileName: position.java $Date: 2011-11-5 下午2:57:32 -0400 2011
 * @since 1.0
 * 
 */
public class Position {
	private int maxWidth = 0;
	private int allHeight = 0;
	private int imgWidth;
	private String fileName;
	private Images img;
	private Hashtable<String, Images> imgTable = new Hashtable<String, Images>();

	public Position(List<String> fileList) throws IOException {
		List<Images> imgList = new ArrayList<Images>();
		int index = fileList.size();
		Iterator<String> it = fileList.iterator();
		while (it.hasNext()) {
			fileName = it.next().toString();
			img = new Images(fileName);
			imgTable.put(fileName, img);
			// repeat-y 需要排除
			if (img.getRepeatAndFloat() == Images.REPEAT_Y) {
				continue;
			}
			imgList.add(img);
			imgWidth = img.getWidth();
			if (imgWidth > maxWidth) {
				maxWidth = imgWidth;
			}
		}
		ComparatorImage ci = new ComparatorImage();
		Collections.sort(imgList, ci);
		int tempWidth = 0;
		int tempHeight = 0;
		for (int i = 0; i < index; i++) {
			img = imgList.get(i);
			if (img.getWidth() == maxWidth || img.getRepeatAndFloat() == Images.REPEAT_X) {
				allHeight += tempHeight;
				tempHeight = 0;
				img.setPositionX(0);
				img.setPositionY(allHeight);
				allHeight += img.getHeight() + 1;
				tempWidth = 0;
				continue;
			}
			if (img.getWidth() + tempWidth <= maxWidth) {
				img.setPositionX(tempWidth);
				img.setPositionY(allHeight);
				tempWidth += img.getWidth() + 1;
				tempHeight = (img.getHeight() + 1) > tempHeight ? (img.getHeight() + 1) : tempHeight;
			} else {
				allHeight += tempHeight;
				tempHeight = 0;
				img.setPositionX(0);
				img.setPositionY(allHeight);
				tempHeight += img.getHeight() + 1;
				tempWidth = img.getWidth() + 1;
			}
		}
		allHeight = allHeight + tempHeight - 1;
	}

	public Hashtable<String, Images> getImgTable() {
		return imgTable;
	}

	public int getMaxWidth() {
		return maxWidth;
	}

	public int getAllHeight() {
		return allHeight;
	}
}
